import {
	getClassifyData,
	getGoodsData,
	getGoodsDetailsData
} from "../../api/goods"
export default {
	namespaced: true,
	state: {
		classifys: [], //菜品分类
		goods: [], //菜品
		goodsDetails: {}, //菜品详情
	},
	mutations: {
		//设置菜品分类
		["SET_CLASSIFYS"](state, payload) {
			state.classifys = payload.classifys;
		},
		//设置菜品
		["SET_GOODS"](state, payload) {
			state.goods = payload.goods;
		},
		//设置菜品详情
		["SET_GOODS_DETAILS"](state, payload) {
			state.goodsDetails = payload.goodsDetails;
		}
	},
	actions: {
		//获取菜品分类
		getClassifys(conText, payload) {
			getClassifyData(payload).then(res => {
				if (res.code == 200) {
					for (let i = 0; i < res.data.length; i++) {
						if (i == 0) {
							res.data[i].active = true;
						} else {
							res.data[i].active = false;
						}
						res.data[i].goodsTop = 0; //对应菜品距顶部的距离
						res.data[i].goodsHeight = 0; //对应菜品的高
						res.data[i].top = 0; //菜品分类距顶部的距离
					}
					conText.commit("SET_CLASSIFYS", {
						classifys: res.data
					});
				} else {
					conText.commit("SET_CLASSIFYS", {
						classifys: []
					});
				}
				if (payload.complete) {
					payload.complete()
				}
			})
		},
		//获取菜品
		getGoods(conText, payload) {
			getGoodsData(payload).then(res => {
				if (res.code == 200) {
					for (let i = 0; i < res.data.length; i++) {
						res.data[i].top = 0;
						res.data[i].left = 0;
						res.data[i].position = "static";
						for (let j = 0; j < res.data[i].goods.length; j++) {
							res.data[i].goods[j].itemTop = 0; //每个菜品的top
							res.data[i].goods[j].amount = 0; //菜品的数量
							res.data[i].goods[j].isAmountInput = false; //是否显示菜品数量输入框
							res.data[i].goods[j].isAmountInputFocus = false; //是否获取菜品数量输入框焦点
							res.data[i].goods[j].new_meal_items = []; //套餐规格
							//重组套餐规格用于购物车判断是否有相同的套餐
							if (res.data[i].goods[j].meal_items) {
								for (let k = 0; k < res.data[i].goods[j].meal_items.length; k++) {
									res.data[i].goods[j].new_meal_items.push({
										"gid": res.data[i].goods[j].meal_items[k].gid
									})
								}
							}
						}
					}
					conText.commit("SET_GOODS", {
						goods: res.data
					});
				} else {
					conText.commit("SET_GOODS", {
						goods: []
					});
				}
			})
		},
		//更新上架或下架的菜品
		getNewGoods(conText, payload) {
			getGoodsData(payload).then(res => {
				if (res.code == 200) {
					if (payload.success) {
						payload.success(res.data);
					}
				}
			})
		},
		//获取菜品详情
		getGoodsDetails(conText, payload) {
			getGoodsDetailsData(payload).then(res => {
				if (res.code == 200) {
					conText.commit("SET_GOODS_DETAILS", {
						goodsDetails: res.data
					});
				}
			})
		}
	}
}